<template>
  <div>
    <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
      <template #orderCode="{ editFormInfo }">
        <el-input
          size="mini"
          :title="editFormInfo.orderCode"
          :disabled="disabled"
          readonly
        >
          <span
            slot="prefix"
            class="orderCode"
            @click="openWorkDetail(editFormInfo, editFormInfo.orderCategory)"
            >{{ editFormInfo.orderCode }}</span
          >
          <el-button
            style="font-size: 16px"
            slot="append"
            icon="el-icon-chat-line-square"
            :disabled="disabled"
            @click="openDialog(editFormInfo)"
          ></el-button>
        </el-input>
      </template>
    </editForm>
    <div class="upload-file">
      <span>附件：</span>
      <attachFormNew
        style="width: 60%"
        :attachSetting="attachSetting"
        ref="attachForm"
        :isDelete="isDelete"
        :disabled="disabled"
      ></attachFormNew>
    </div>
    <dialogPublic
      :title="title"
      :show.sync="show"
      v-if="show"
      :fullscreen="true"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <orderList :searchData="searchData" ref="orderList"></orderList>
    </dialogPublic>
  </div>
</template>

<script>
import orderList from "../orderList.vue";
import { queryEquipsByOrderId } from "@/api/orderManagement/common.js";
import { queryPageList } from "@/api/orderManagement/orderCommon.js";
export default {
  components: {
    orderList,
  },
  props: {
    basicInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    status: {
      type: Number,
    },
  },
  data() {
    return {
      show: false,
      disabled: false,
      isDelete: false,
      minTime: null,
      searchData: {
        statusList: ["WAIT_EXECUTE", "IN_EXECUTE"],
      },
      basicConfig: {
        labelWidth: "160px",
        itemArr: [
          {
            label: "相关工单编号",
            prop: "orderCode",
            type: "text",
            required: true,
            disabled: true,
            span: 8,
          },
          {
            label: "检修设备",
            prop: "equipmentName",
            idsStr: "equipmentId",
            type: "majorEquipment",
            //equipmentType:"equipmentType",
            placeholder: "非机组/主变/线路等主要设备无需选择",
            multiple: false,
            required: false,
            disabled: false,
            deptManage: "deptManages",
            deptManageName: "deptManageNames",
            span: 8,
            choseData: "equipments",
            methods: (data, formData) => {
              let equipments = [
                {
                  equipmentId: data.equipmentId,
                  equipmentName: data.equipmentName,
                },
              ];
              this.$refs.basicForm.setFormItem("equipments", [data]);
              this.$refs.basicForm.setFormItem("equipmentList", equipments);
              if (JSON.stringify(data) != "{}") {
                this.setDeptManage(data, formData);
              } else {
                this.basicConfig.itemArr[2].disabled = false;
                this.$refs.basicForm.setFormItem("deptManageArr", null);
                this.$refs.basicForm.setFormItem("deptManage", null);
                this.$refs.basicForm.setFormItem("deptManageName", null);
              }
            },
          },
          {
            label: "设备管理单位",
            prop: "deptManageName",
            propArr: "deptManageArr",
            idsStr: "deptManage",
            type: "dept-select",
            option: [],
            required: true,
            disabled: false,
            span: 8,
          },
          {
            label: "检修类型",
            prop: "orderType",
            type: "select",
            required: true,
            span: 8,
            selectOption: this.$store.getters.dirtData(
              "order_application_orderType"
            ),
          },
          {
            label: "申请检修时间",
            prop: "delayTime",
            type: "datetimerange",
            isHide: false,
            required: true,
            span: 8,
            // rules: {
            //   message: "请选择未来的时间段",
            //   trigger: "blur",
            //   validator: (rule, value, callback) => {
            //     this.checkTime(rule, value, callback);
            //   },
            // },
            pickerOptions: {
              disabledDate: (time) => {
                let minTime = new Date(
                  `${this.$utils.getCurrentDate(1)} 00:00`
                ).getTime();
                return time.getTime() < minTime;
              },
            },
            methods: (val) => {
              if (val) {
                let times =
                  new Date(val[1]).getTime() - new Date(val[0]).getTime();
                let hours = times / (60 * 60 * 1000);
                this.$refs.basicForm.setFormItem(
                  "delayTimeLength",
                  hours.toFixed(2)
                );
                this.$refs.basicForm.setFormItem("startTime", val[0]);
                this.$refs.basicForm.setFormItem("endTime", val[1]);
              }
            },
          },

          {
            label: "申请检修工作时长(h)",
            prop: "delayTimeLength",
            type: "text",
            required: true,
            disabled: true,
            span: 8,
          },
          {
            label: "申请人",
            prop: "createByName",
            type: "text",
            required: true,
            disabled: true,
            span: 8,
          },
          {
            label: "检修内容",
            prop: "context",
            type: "textarea",
            required: true,
            span: 24,
            rows: 3,
          },
          {
            label: "对系统的影响",
            prop: "influence",
            type: "textarea",
            rows: 3,
            required: true,
            span: 24,
          },
        ],
      },
      formData: {
        createByName: this.$store.getters.userInfo.name,
        equipmentList: [],
        //equipmentType:"UNIT"
      },
      attachSetting: {},
    };
  },
  created() {
    this.minTime = new Date(`${this.$utils.getCurrentTime(1)} 00:00`).getTime();
    if (this.status > 0) {
      this.basicConfig.itemArr.map((i) => (i.disabled = true));
      this.disabled = true;
    } else {
      this.basicConfig.itemArr.map((i) => {
        if (i.prop != "delayTimeLength" && i.prop != "createByName") {
          i.disabled = false;
        }
      });
      this.disabled = false;
      if (this.status == 0) {
        this.isDelete = true;
      }
    }
  },
  watch: {
    basicInfo: {
      handler(val) {
        this.init(val);
      },
      deep: true,
    },
    status: {
      handler(val) {
        if (val > 0) {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.disabled = true;
        } else {
          this.basicConfig.itemArr.map((i) => {
            if (i.prop != "delayTimeLength" && i.prop != "createByName") {
              i.disabled = false;
            }
          });
          if (
            this.basicInfo.equipmentList &&
            this.basicInfo.equipmentList.length > 0
          ) {
            this.basicConfig.itemArr[2].disabled = true;
          } else {
            this.basicConfig.itemArr[2].disabled = false;
          }
          this.disabled = false;
          if (this.status == 0) {
            this.isDelete = true;
          }
        }
      },
    },
  },
  methods: {
    //初始化信息
    init(val) {
      let data = JSON.parse(JSON.stringify(val));
      this.attachSetting = {
        businessId: data.id,
      };
      data.delayTime = [val.startTime, val.endTime];
      let times =
        new Date(data.endTime).getTime() - new Date(data.startTime).getTime();
      let hours = times / (60 * 60 * 1000);
      data.delayTimeLength = hours;
      if (data.equipmentList) {
        data.equipmentId = data.equipmentList
          .map((item) => item.equipmentId)
          .join(", ");
        data.equipmentName = data.equipmentList
          .map((item) => item.equipmentName)
          .join(", ");
      }
      this.formData = data;
      let deptOption = [
        {
          label: this.formData.deptManageName,
          value: this.formData.deptManage,
          id: this.formData.deptManage,
          name: this.formData.deptManageName,
        },
      ];
      setTimeout(() => {
        this.$refs.basicForm.setItemOption("deptManageName", deptOption);
        this.$refs.basicForm.setFormItem(
          "deptManageArr",
          this.formData.deptManage
        );
      }, 0);
    },
    //打开弹框
    openDialog(formData) {
      this.title = "选择工单";
      this.show = true;
    },
    openWorkDetail(row, type) {
      switch (type) {
        case "defect":
          this.goDetailPage(row, "defectOrderDetails", "detail");
          break;
        case "maintain":
          this.goDetailPage(row, "normalMaintenanceDetails", "detail");
          break;
        case "overhaul":
          this.goDetailPage(row, "overhaulDetails", "detail");
          break;
        case "experiment":
          this.goDetailPage(row, "experimentOrderDetails", "detail");
          break;
        default:
          this.goDetailPage(row, "patrolOrderDetails", "detail");
          break;
      }
    },
    //设置设备管理单位
    setDeptManage(data, formData) {
      if (formData.hasOwnProperty("deptManage") && formData.deptManage) {
        if (data.deptManage != formData.deptManage) {
          let h = this.$createElement;
          this.$confirm("", {
            message: h("span", [
              h("span", "所选设备的管理单位"),
              h(
                "span",
                { style: "color:#40b6ff" },
                ` [${data.deptManageName}] `
              ),
              h(
                "span",
                "与该检修申请单的设备管理单位不一致，是否重新选择或覆盖"
              ),
            ]),
            confirmButtonText: "覆盖",
            cancelButtonText: "重新选择",
            distinguishCancelAndClose: true,
            type: "warning",
          })
            .then(() => {
              this.$refs.basicForm.setFormItem("deptManage", data.deptManage);
              this.$refs.basicForm.setFormItem(
                "deptManageName",
                data.deptManageName
              );
              let deptOption = [
                {
                  label: data.deptManageName,
                  value: data.deptManage,
                  id: data.deptManage,
                  name: data.deptManageName,
                },
              ];
              this.$refs.basicForm.setItemOption("deptManageName", deptOption);
              setTimeout(() => {
                this.$refs.basicForm.setFormItem(
                  "deptManageArr",
                  data.deptManage
                );
                this.basicConfig.itemArr[2].disabled = true;
              }, 0);
            })
            .catch((action) => {
              let item = this.basicConfig.itemArr[1];
              this.$refs.basicForm.goSeleteOrgMember(item, item.type);
            });
        }
      } else {
        this.$refs.basicForm.setFormItem("deptManage", data.deptManage);
        this.$refs.basicForm.setFormItem("deptManageName", data.deptManageName);
        let deptOption = [
          {
            label: data.deptManageName,
            value: data.deptManage,
            id: data.deptManage,
            name: data.deptManageName,
          },
        ];
        setTimeout(() => {
          this.$refs.basicForm.setItemOption("deptManageName", deptOption);
          this.$refs.basicForm.setFormItem("deptManageArr", data.deptManage);
        }, 0);
        this.basicConfig.itemArr[2].disabled = true;
      }
    },
    //跳转到详情页
    goDetailPage(row, router, type) {
      const { href } = this.$router.resolve({
        name: router,
        query: {
          id: row ? row.orderId : "",
          pageType: type ? type : "",
        },
      });
      window.open(href, "_blank");
    },
    setApplication(orderId, orderCode) {
      let queryData = {
        id: orderId,
      };
      queryPageList(queryData).then((res) => {
        let data = res.data.list[0];
        this.$refs.basicForm.setFormItem("orderCode", data.code);
        this.$refs.basicForm.setFormItem("orderId", data.id);
        this.$refs.basicForm.setFormItem("orderCategory", data.orderType);
        this.$refs.basicForm.setFormItem("deptManage", data.deptManage);
        this.$refs.basicForm.setFormItem("deptManageName", data.deptManageName);
        let deptOption = [
          {
            label: data.deptManageName,
            value: data.deptManage,
            id: data.deptManage,
            name: data.deptManageName,
          },
        ];
        setTimeout(() => {
          this.$refs.basicForm.setItemOption("deptManageName", deptOption);
          this.$refs.basicForm.setFormItem("deptManageArr", data.deptManage);
        }, 0);
        //this.getEquipmentById(data.id);
        this.$emit("getExecuteInfo", data);
      });
    },
    //选择工单
    doSubmit() {
      let data = this.$refs.orderList.getselectData();
      let formData = this.$refs.basicForm.getCurrentData();
      this.$refs.basicForm.setFormItem("orderCode", data.code);
      this.$refs.basicForm.setFormItem("orderId", data.id);
      this.$refs.basicForm.setFormItem("orderCategory", data.orderType);
      if (!formData.hasOwnProperty("deptManage") || !formData.deptManage) {
        this.$refs.basicForm.setFormItem("deptManage", data.deptManage);
        this.$refs.basicForm.setFormItem("deptManageName", data.deptManageName);
        let deptOption = [
          {
            label: data.deptManageName,
            value: data.deptManage,
            id: data.deptManage,
            name: data.deptManageName,
          },
        ];
        setTimeout(() => {
          this.$refs.basicForm.setItemOption("deptManageName", deptOption);
          this.$refs.basicForm.setFormItem("deptManageArr", data.deptManage);
        }, 0);
      }

      //this.getEquipmentById(data.id);
      this.$emit("getExecuteInfo", data);
      this.show = false;
    },
    //获取工单关联设备
    getEquipmentById(id) {
      queryEquipsByOrderId({ id: id }).then((res) => {
        let equipName = res.data.map((item) => item.equipmentName).join(", ");
        let equipId = res.data.map((item) => item.equipmentId).join(", ");
        let equipments = res.data.map((item) => {
          const obj = {
            equipmentId: item.equipmentId,
            equipmentName: item.equipmentName,
          };
          return obj;
        });
        this.$refs.basicForm.setFormItem("equipmentName", equipName);
        this.$refs.basicForm.setFormItem("equipmentId", equipId);
        this.$refs.basicForm.setFormItem("equipmentList", equipments);
      });
    },
    //获取基本信息
    async getBasicInfo() {
      let formData = await this.$refs.basicForm.getFormData();
      return formData;
    },
    //上传文件
    uploadFile(id) {
      new Promise((resolve, reject) => {
        this.attachSetting = { businessId: id };
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachForm.doSubmitFiles();
      });
    },
    doClose() {
      this.show = false;
    },
  },
};
</script>

<style lang="less" scoped>
.upload-file {
  margin-left: 70px;
  text-align: left;
  display: flex;
  span {
    margin-right: 10px;
  }
}
.orderCode {
  line-height: 28px;
  color: #40b6ff;
  margin-left: 10px;
  cursor: pointer;
}
</style>